<template>
  <div class="nav-header">
    <div class="header-content">
      <!-- Logo -->
      <div class="logo">
        <router-link
          to="/"
          @click="clearSearchText"
        >
          CC-VIDEO
        </router-link>
      </div>

      <!-- 搜索框 -->
      <div class="search-section">
        <a-dropdown
          v-model:visible="showSearchDropdown"
          trigger="click"
          :overlay-style="{ marginTop: '-1px' }"
          :getPopupContainer="triggerNode => triggerNode.parentNode"
          :trigger-props="{ animation: [] }"
        >
          <a-input-search
            ref="searchRef"
            v-model:value="searchText"
            placeholder="搜索视频"
            @search="onSearch"
            @keyup.enter="onSearch(searchText)"
            size="large"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input-search>

          <template #overlay>
            <div class="search-dropdown">
              <!-- 热搜 -->
              <div class="hot-searches">
                <h3><strong>今日热搜</strong></h3>
                <ul v-if="hotSearchList?.length > 0">
                  <li
                    v-for="(item, index) in hotSearchList"
                    :key="index"
                    @click="onSearch(item)"
                  >
                    <span
                      class="rank"
                      :class="{ top3: index < 3 }"
                    >
                      {{ index + 1 }}
                    </span>
                    <span class="keyword">{{ item }}</span>
                  </li>
                </ul>

                <div v-else>
                  <a-empty />
                </div>
              </div>

              <!-- 搜索历史 -->
              <div
                class="search-history"
                v-if="searchHistory.length"
              >
                <div class="history-header">
                  <h3><strong>搜索历史</strong></h3>
                  <a-button
                    type="link"
                    @click="clearHistory"
                  >
                    清空
                  </a-button>
                </div>
                <ul>
                  <li
                    v-for="(item, index) in searchHistory"
                    :key="index"
                    @click="onSearch(item)"
                  >
                    <ClockCircleOutlined />

                    <span>
                      {{ item }}
                    </span>

                    <CloseOutlined
                      class="delete-btn"
                      @click.stop="removeHistory(index)"
                    />
                  </li>
                </ul>
              </div>
            </div>
          </template>
        </a-dropdown>
      </div>

      <!-- 右侧功能区 -->
      <div class="right-section">
        <!-- a-badge 会自动忽略 0，因此不需要加 v-if -->
        <a-badge :count="unreadCount">
          <div
            class="nav-item"
            @click="goTo('/message')"
          >
            <MessageOutlined />
            <span>私信</span>
          </div>
        </a-badge>

        <div
          class="nav-item"
          @click="goTo('/subscriptions')"
        >
          <StarOutlined />
          <span>订阅</span>
        </div>

        <div
          class="nav-item"
          @click="goTo('/favorites')"
        >
          <HeartOutlined />
          <span>收藏</span>
        </div>

        <div
          class="nav-item"
          @click="goTo('/history')"
        >
          <HistoryOutlined />
          <span>历史</span>
        </div>

        <a-button
          type="primary"
          size="large"
          class="login-btn"
          @click="isLoginDialogVisible = true"
          v-if="!isLogin"
        >
          登录
        </a-button>

        <a-dropdown
          placement="bottom"
          v-else
        >
          <template #overlay>
            <a-menu>
              <a-menu-item @click="goTo(`/profile?userId=${userState.getUserId}`)">
                <span>个人中心</span>
              </a-menu-item>
              <a-menu-item @click="goTo('/upload')">
                <span>上传视频</span>
              </a-menu-item>
              <a-menu-item @click="goTo('/manage')">
                <span>视频管理</span>
              </a-menu-item>
              <a-menu-item @click="goTo('/modifyPassword')">
                <span>修改密码</span>
              </a-menu-item>
              <a-menu-item @click="handleLogout">
                <span>退出登录</span>
              </a-menu-item>
            </a-menu>
          </template>
          <a-avatar
            :src="userState.getUserAvatar"
            style="width: 45px; height: 45px; cursor: pointer"
          />
        </a-dropdown>
      </div>
    </div>

    <LoginForm
      v-if="!isLogin"
      v-model="isLoginDialogVisible"
    />
  </div>
</template>

<script setup lang="ts">
import {
  SearchOutlined,
  HistoryOutlined,
  StarOutlined,
  MessageOutlined,
  HeartOutlined,
  ClockCircleOutlined,
  CloseOutlined
} from '@ant-design/icons-vue'
import { useCache } from '@/utils/useCache'
import LoginForm from '../LoginForm/index.vue'
import { getAccessToken } from '@/utils/auth'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/store/modules/user'
import { getHotSearch } from '@/api/search'
import { SseRespVO } from '@/types/sse'

const userState = useUserStore()

const router = useRouter()
const { wsCache } = useCache()
const SEARCH_HISTORY_KEY = 'search_history'

// 搜索相关
const searchRef = ref()
const searchText = ref('')
const showSearchDropdown = ref(false)
const searchHistory = ref<string[]>([])

// 登录相关
const isLoginDialogVisible = ref(false)
const isLogin = ref(false)

const hotSearchList = ref<String[]>()

/**
 * 获取搜索历史
 */
const loadSearchHistory = () => {
  searchHistory.value = wsCache.get(SEARCH_HISTORY_KEY) || []
}

/**
 * 保存搜索历史
 */
const saveSearchHistory = (keyword: string) => {
  if (!keyword.trim()) return
  const history = searchHistory.value
  // 删除重复项
  const index = history.indexOf(keyword)
  if (index > -1) {
    history.splice(index, 1)
  }
  // 添加到开头
  history.unshift(keyword)
  // 只保留最近10条
  if (history.length > 10) {
    history.pop()
  }
  wsCache.set(SEARCH_HISTORY_KEY, history)
}

/**
 * 删除单条历史记录
 */
const removeHistory = (index: number) => {
  searchHistory.value.splice(index, 1)
  wsCache.set(SEARCH_HISTORY_KEY, searchHistory.value)
}

/**
 * 清空历史记录
 */
const clearHistory = () => {
  searchHistory.value = []
  wsCache.delete(SEARCH_HISTORY_KEY)
}

/**
 * 搜索处理
 */
const onSearch = (value: string) => {
  if (!value.trim()) return
  saveSearchHistory(value)

  searchText.value = value
  if (router.currentRoute.value.path === '/search') {
    router.push(`/search?keyword=${value}`)
  } else {
    window.open(`/search?keyword=${value}`)
  }

  showSearchDropdown.value = false
}

const clearSearchText = () => {
  searchText.value = ''
}

/**
 * 页面跳转
 */
const goTo = (path: string) => {
  if (!getAccessToken()) {
    message.error('请登录')
    return
  }
  window.open(path)
}

const unreadCount = ref(0)
let eventSource = null
onMounted(async () => {
  // 获取热搜记录
  hotSearchList.value = await getHotSearch()

  // 加载搜索历史记录
  loadSearchHistory()

  if (getAccessToken()) {
    isLogin.value = true

    // 连接 SSE，读取未读消息个数
    eventSource = new EventSource(
      `${import.meta.env.VITE_BASE_API}/platform/message/sse/${userState.getUserId}`
    )

    eventSource.onmessage = event => {
      const message: SseRespVO = JSON.parse(event.data)
      if (message.type === 'unreadCount') {
        const data = message.data
        if (data && data?.totalCount) {
          unreadCount.value = data?.totalCount
        } else {
          unreadCount.value = 0
        }
      }
    }
  }
})

onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
  }
})

/**
 * 如果当前页面是搜索页，且搜索关键字为空，则去 keyword 获取
 */
watch(
  () => router.currentRoute.value.path,
  path => {
    if (path === '/search' && !searchText.value && router.currentRoute.value.query.keyword) {
      searchText.value = router.currentRoute.value.query.keyword as string
    }
  }
)

/**
 * 退出登录
 */
const handleLogout = () => {
  Modal.confirm({
    title: '提示',
    content: '确定要退出登录吗？',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: async () => {
      await userState.logout()
      window.location.reload()
    }
  })
}
</script>

<style scoped>
.nav-header {
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  height: 64px;
  display: flex;
  align-items: center;
  background: #fff;
  justify-content: space-between;
}

.logo {
  font-size: 38px;
  font-weight: bold;
  margin-left: 0;
  font-family: 'Segoe UI', sans-serif;
}

.logo a {
  color: #1890ff;
  text-decoration: none;
}

.search-section {
  width: 500px;
  flex: 0 0 500px;
  margin: 0 48px;
  display: flex;
  align-items: center;
  position: relative;
}

.search-section :deep(.ant-input-group) {
  position: relative;
}

.search-section :deep(.ant-input-affix-wrapper) {
  border-radius: 24px 0 0 24px;
  height: 44px;
  display: flex;
  align-items: center;
  border: 1px solid #dfe1e5;
  border-right: 0;
  background-color: #fff;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(32, 33, 36, 0.1);
}

.search-section :deep(.ant-input-affix-wrapper:hover),
.search-section :deep(.ant-input-search-button:hover) {
  border-color: #dfe1e5;
  box-shadow: 0 1px 6px rgba(32, 33, 36, 0.15);
}

.search-section :deep(.ant-input) {
  background-color: transparent;
  border: none;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  padding-left: 8px;
}

.search-section :deep(.ant-input-search-button) {
  height: 44px;
  border-radius: 0 24px 24px 0;
  width: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #dfe1e5;
  border-left: 0;
  background: #fff;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(32, 33, 36, 0.1);
}

.search-section :deep(.anticon) {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9aa0a6;
  font-size: 20px;
}

.search-dropdown {
  background: #fff;
  padding: 16px;
  width: 500px;
  border: none;
  border-bottom-left-radius: 24px;
  border-bottom-right-radius: 24px;
  position: relative;
  margin-top: -2px;
  box-shadow: 0 4px 6px rgba(32, 33, 36, 0.2);
}

.search-section :deep(.ant-dropdown-open) {
  box-shadow: none !important;
}

.hot-searches h4,
.search-history h4 {
  margin-bottom: 12px;
  color: #666;
  font-size: 14px;
}

.hot-searches li {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.2s;
  cursor: pointer;
}

.rank {
  width: 20px;
  margin-right: 12px;
  color: #999;
}

.rank.top3 {
  color: #ff4d4f;
  font-weight: bold;
}

.hot-searches li:hover,
.search-history li:hover {
  background-color: #f8f9fa;
}

.search-history {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-history li {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.2s;
  color: #666;
  cursor: pointer;
}

.search-history li :deep(.anticon) {
  margin-right: 8px;
  color: #9aa0a6;
}

.delete-btn {
  margin-left: auto;
  color: #9aa0a6;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

.search-history li:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  color: #666;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 32px;
  margin-right: 0;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #666;
}

.nav-item:hover {
  color: #1890ff;
}

.nav-item :deep(.anticon) {
  font-size: 22px;
  margin-bottom: 4px;
}

.nav-item span {
  font-size: 13px;
  line-height: 1;
}

.login-btn {
  padding: 0 24px;
  height: 36px;
  font-size: 15px;
}

/* 只保留边框相关样式 */
.search-section :deep(.ant-dropdown-open .ant-input-affix-wrapper),
.search-section :deep(.ant-dropdown-open .ant-input-search-button) {
  border-bottom: none;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}

.search-section :deep(.ant-input-search-button:hover) {
  background-color: #f8f9fa;
  border-color: #dfe1e5;
}

.keyword {
  cursor: pointer;
}

/* 当下拉框显示时的搜索框样式 */
.search-section :deep(.ant-dropdown-open) {
  box-shadow: 0 2px 8px rgba(32, 33, 36, 0.15);
}

/* 搜索框悬浮和聚焦状态 */
.search-section:hover :deep(.ant-input-affix-wrapper),
.search-section:hover :deep(.ant-input-search-button),
.search-section :deep(.ant-input-affix-wrapper-focused),
.search-section :deep(.ant-input-search-button:focus) {
  box-shadow: 0 1px 6px rgba(32, 33, 36, 0.28);
  border-color: rgba(223, 225, 229, 0);
}
</style>
